#!/usr/bin/env python

import sys

# Temporary hack to point to the install of PyQT from macports for Snow Leopard
if sys.platform == "darwin":
    try:
        sys.path.append("/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages")
    except:
        pass

import httplib
try:
    from PyQt4.QtCore import (Qt, SIGNAL, pyqtSignature)
    from PyQt4.QtGui import *
except:
    print("You need to have PyQT4 installed. Use your package manager to install it")

import DharmaInterface
import DharmaEncoderAbout
import encoderlib
import SimpleDialog

MAC = True
try:
    from PyQt4.QtGui import qt_mac_set_native_menubar
except ImportError:
    MAC = False
    
__version__ = "0.5"

class DharmaEncoder(QMainWindow, DharmaInterface.Ui_mainWindow):
    """ Reimplementation of the imported Ui_mainWindow class """
    def __init__(self, parent=None):
        super(DharmaEncoder, self).__init__(parent)
        self.setupUi(self)
        if MAC == True:
            qt_mac_set_native_menubar(False)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)
        self.progressBar.hide()
        
        # Create the actions for the menus
        self.connect(self.actionQuit, SIGNAL("triggered()"), self.close)
        self.connect(self.actionAbout_DharmaEncoder, SIGNAL("triggered()"), self.display_about)
        self.connect(self.actionCheck_for_Update, SIGNAL("triggered()"), self.check_update)
        

        # Create the actions for the buttons
        self.connect(self.encodeButton, SIGNAL("clicked()"), self.encode_values)
        self.connect(self.encodeWrapButton, SIGNAL("clicked()"), self.wrap_encode)
        self.connect(self.decodeButton, SIGNAL("clicked()"), self.decode_values)
        self.connect(self.decodeWrapButton, SIGNAL("clicked()"), self.wrap_decode)
        

    def encode_values(self):
        """ Encode the values from the encodeEdit """
        
        encode_value = str(self.encodeEdit.toPlainText())
        encode_method = self.encodingMethodCombo.currentText()
        value = ""

        self.progressBar.show()
        
        if encode_method == "URL":
            value = encoderlib.url_encode(encode_value)
        elif encode_method == "Full URL":
            value = encoderlib.full_url_encode(encode_value)
        elif encode_method == "Base64":
            value = encoderlib.base64_encode(encode_value)
        elif encode_method == "HTML Entity":
            value = encoderlib.html_entity_encode(encode_value)
        elif encode_method == "Hex":
            value = encoderlib.hex_encode(encode_value)
        elif encode_method == "Hex Entity":
            value = encoderlib.hex_entity_encode(encode_value)
        elif encode_method == "MD5 Hash":
            value = encoderlib.md5_hash(encode_value)
        elif encode_method == "SHA1 Hash":
            value = encoderlib.sha1_hash(encode_value)
        elif encode_method == "SQL CHAR String":
            value = encoderlib.sqlchar_encode(encode_value)
        elif encode_method == "Oracle chr String":
            value = encoderlib.oraclechr_encode(encode_value)
        elif encode_method == "Unicode %u00":
            value = encoderlib.unicode_encode(encode_value)
        elif encode_method == "Escape HTML/XML":
            value = encoderlib.escape_xml(encode_value)
        elif encode_method == "Decimal":
            value = encoderlib.decimal_convert(encode_value)
        elif encode_method == "Decimal Entity":
            value = encoderlib.decimal_entity_encode(encode_value)
        elif encode_method == "ROT13":
            value = encoderlib.rot13_encode(encode_value)
            
        self.decodeEdit.setText(value)
        self.progressBar.hide()
        
    def wrap_encode(self):
        """ Wrap the encode chars """
        
        encode_value = str(self.encodeEdit.toPlainText())
        wrap_value = self.encodingWrapCombo.currentText()
        
        if wrap_value == "<script></script>":
            value = "<script>" + encode_value + "</script>"
        elif wrap_value == "<ScRiPt></ScRiPt>":
            value = "<ScRiPt>" + encode_value + "</ScRiPt>"
        elif wrap_value == "alert(...)":
            value = "alert(" + encode_value + ")"
        elif wrap_value == '"Javascript:..."':
            value = '"javascript:' + encode_value + '"'
        elif wrap_value == '<img src="..."':
            value = '<img src="' + encode_value + '">'
          
        self.encodeEdit.setPlainText(value)
        
    def decode_values(self):
        """ Decode the values from the decodeEdit """
        
        decode_value = str(self.decodeEdit.toPlainText())
        decode_method = self.decodeMethodCombo.currentText()
        value = ""
        
        self.progressBar.show()
        
        if decode_method == "URL":
            value = encoderlib.url_decode(decode_value)
        elif decode_method == "Full URL":
            value = encoderlib.fullurl_decode(decode_value)
        elif decode_method == "Base64":
            value = encoderlib.base64_decode(decode_value)
        elif decode_method == "Hex Entity":
            value = encoderlib.hexentity_decode(decode_value)
        elif decode_method == "Unescape HTML/XML":
            value = encoderlib.unescape_xml(decode_value)
        elif decode_method == "Unicode %u00":
            value = encoderlib.unicode_decode(decode_value)
        elif decode_method == "ROT13":
            value = encoderlib.rot13_decode(decode_value)
            
        self.encodeEdit.setText(value)
        self.progressBar.hide()
        
    def wrap_decode(self):
        """ Wrap the Decode Values """
        
        decode_value = str(self.decodeEdit.toPlainText())
        wrap_value = self.decodeWrapCombo.currentText()
        
        if wrap_value == "<script></script>":
            value = "<script>" + decode_value + "</script>"
        elif wrap_value == "<ScRiPt></ScRiPt>":
            value = "<ScRiPt>" + decode_value + "</ScRiPt>"
        elif wrap_value == "alert(...)":
            value = "alert(" + decode_value + ")"
        elif wrap_value == '"javascript:..."':
            value = '"javascript:' + decode_value + '"'
        elif wrap_value == '<img src="..."':
            value = '<img src="' + decode_value + '">'
          
        self.decodeEdit.setPlainText(value)
            
        
    def display_about(self):
        dialog = EncoderAboutDialog()
        dialog.exec_()
        
    def check_update(self):
        
        UpdateDialog = DumbDialog(self)
        
        try:
            
            connection = httplib.HTTPConnection("hexsec.com")
            connection.request("GET", "/VersionCheck/DharmaEncoder/current")
            response = connection.getresponse()
            
            current = response.read()
            connection.close()
            
            updatemessage = "There is an update available. Visit http://hexsec.com/labs \
                            for more information"
            currentmessage = "Your version of DharmaEncoder is current"
            
            if __version__ < current.rstrip():
                UpdateDialog.messageLabel.setText(updatemessage)
            else:
                UpdateDialog.messageLabel.setText(currentmessage)
                
            UpdateDialog.exec_()
        
        except:
            
            error = "There was an error checking for updates. Please try again later"
            UpdateDialog.messageLabel.setText(error)
            UpdateDialog.exec_()
            
    def display_hello(self):
        """ Function to quit the application """
        
        print("hello world")
        
class EncoderAboutDialog(QDialog, DharmaEncoderAbout.Ui_aboutDialog):
    """ About dialog for DharmaEncoder """
    
    def __init__(self, parent=None):
        super(EncoderAboutDialog, self).__init__(parent)
        self.setupUi(self)
        version_string = "Version - " + __version__
        self.versionLabel.setText(version_string)
        
class DumbDialog(QDialog, SimpleDialog.Ui_simpleDialog):
    """ A dumb dialog to display messages """
    
    def __init__(self, parent=None):
        super(DumbDialog, self).__init__(parent)
        self.setupUi(self)
        

def main():
    
    app = QApplication(sys.argv)
    mainWindow = DharmaEncoder()
    mainWindow.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()